// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue"
import App from "./App"
import router from "./router"
import store from "./store"
import "@/assets/font-web/SourceHanSans.css"
import "@/assets/icon-font/iconfont.css"
import "@/assets/style/base.scss"
import "@/assets/style/element.scss"
import "@/utils/directives.js"
import vueComponent from '@/components/index'
Vue.use(vueComponent)

//elementUi
import ElementUI from "element-ui"
Vue.use(ElementUI, {size: 'small'})
import '@/assets/style/element-variables.scss'

// 自定义element Ui主题
//echarts数据统计
import echarts from "echarts"
Vue.prototype.$echarts = echarts

//axios请求
import axios from "axios"
//axios 请求超时  axios挂载在vue上  axios没有use
axios.defaults.headers.post['Content-Type'] = 'application/json';
//axios.defaults.baseURL = 'http://192.168.2.16:8080';
axios.defaults.timeout = 30000;
Vue.prototype.$http = axios;

// h5 富文本工具
import "font-awesome.css"
import initRichText from '@/components/html5Editor'
initRichText()
//参数拼
import qs from "qs"
Vue.prototype.qs = qs;

// 全局过滤器
import custom from '@/utils/filter.js'
Object.keys(custom).forEach(key => {
  Vue.filter(key, custom[key])
})

//关闭vue启动时生成生产
Vue.config.productionTip = false
Vue.prototype.isChina = isChina
Vue.prototype.comConfig = comConfig
// http request 拦截器 放在vue 对象前面 防止第一次加载不执行
axios.interceptors.request.use(
  config => {
    const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
    const token = JSON.parse(loginMsg).token
    const expire = JSON.parse(loginMsg).expire
    if (token && expire) {
      config.headers.token = token;
      config.headers.expire = expire;
    }
    return config
  }
)
// http response 拦截器  放在vue 对象前面 防止第一次加载不执行
axios.interceptors.response.use(
  res => {
    //有返回数据就清空上当前请求记录
    if (!res.data.success && res.data.errorCode && res.data.errorCode == 'SC_UNAUTHORIZED') {
      sessionStorage.removeItem('loginMsg')
      store.commit('set_LoginInfo', {})
      Vm.$message({ type: 'error', message: res.data.errorMsg || '登录已过期，请重新登录！' })
      router.replace('/main/login')
      return false
    } else {
      if (!res.data.success) Vm.$message.error(res.data.errorMsg || '请求错误')
      return res
    }
  },
  //判断 中断请求/请求超时/其他错误
  error => {
    let _error = error.config;
    if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 && !_error._retry) {
      Vm.$message({
        showClose: true,
        message: '请求超时！',
        type: 'error'
      });
      console.log('【请求超时】' + error.message)
      return Promise.reject({'timeout': error.message})

    } else {
      Vm.$message({
        showClose: true,
        message: '服务器未响应！',
        type: 'error'
      });
      console.log('【请求错误】' + error.message)
      return Promise.reject({'state': {'errorMsg': error.response.data, 'state': error.response.status}})
    }
  }
)

const version = process.env.VERSION
const ifVersionCorrect = function(to, from, next) {
  if (to.path === '/main/login') {
    next()
  } else {
    const loginMsg = sessionStorage.getItem('loginMsg') || '{}'
    if (!loginMsg || Object.keys(JSON.parse(loginMsg)).length === 0) {
      next({ path: '/main/login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
  } // 不适合调用参数, 如next('/')会出现死循环，原因在于参数情况下会第二次执行router.beforeEach的回调函数
}
const checkVersion = function(to, from, next) {
  console.info('当前版本：', version)
  axios.get(`${window.location.origin + window.location.pathname}assets/version.json?_=${Math.random()}`).then((response) => { // 访问前端服务器获取版本号
    if (response.status === 200 && version !== response.data.version) {
      location.reload(true)
      // Vm.$alert('发现新版本，确认后更新！' ,'系统通知!').then(() => {
      //   location.reload(true)
      // })
      return
    }
    ifVersionCorrect(to, from, next);
  }).catch((err) => {
    console.error('checkVersion', err)
    ifVersionCorrect(to, from, next)
  })
}

//路由拦截登录    写在new Vue前 可以防止直接输入url地址不跳转登录
router.beforeEach((to, from, next) => {
  if (version) { // VERSION在prod.env中配置，作为区分生产环境
    checkVersion(to, from, next)
  } else {
    ifVersionCorrect(to, from, next)
  }
})

let Vm = new Vue({
  el: '#app',
  store,//使用store
  router,
  render: h => h(App)
})
